#!/bin/sh
# Copyright (C) 2024-2025 KoudaiPC Computer Technologies Co., Ltd.
# script name: huangdi-customize-openwrt.sh
# author: david921518@qq.com

. /usr/lib/kpc/posix-arrays.sh

################
# global vars
GLB_WORK_DIR=
GLB_DONE_FILE=
GLB_ROOT_DEV=
GLB_ROOT_PART=
GLB_ROOT_DISK=
GLB_ROOT_PART_NUM=
GLB_ADMIN_SSH_PORT=
GLB_ADMIN_HTTP_PORT=
GLB_ADMIN_HTTPS_PORT=
GLB_ADMIN_TTYD_PORT=
GLB_ADMIN_PASSWORD=
GLB_ADMIN_USERNAME=
GLB_LC_LANGUAGE=
GLB_LC_CHARSET=
GLB_SWAP_FILESIZE=
GLB_REBOOT_COUNTER=
#GLB_INSTALLED_PKGS=()
declare_i_arr GLB_INSTALLED_PKGS
GLB_NUM_INSTALLED_PKGS=0
GLB_REAL_PATH=
################

whoami=$(which whoami)
if [ x"$whoami" == x ]; then
  user="$USER"
else
  user=$(whoami)
fi

log_kmsg_path="/dev/kmsg"
log_con_path="/dev/tty1"

# 定义日志格式-前缀
log_prefix="[customize-openwrt]"
# 定义日志目录和文件名
if [ "$user" == "root" ]; then
  log_file_dir="/var/log/kpc/huangdi"
else
  log_file_dir=~/.local/log/kpc/huangdi
fi
log_file_name="firstboot.log"
log_file_path="$log_file_dir/$log_file_name"

function log_init()
{
  # 文件不存在则创建
  if [ ! -d "$log_file_dir" ]; then
    mkdir -p $log_file_dir
    chmod -R 755 $log_file_dir
  fi
  if [ ! -f "$log_file_path" ]; then
    touch $log_file_path
  fi
}

# 定义日志打印格式
function log()
{
  # 定义日志时间格式
  local curtime=$(date "+%Y-%m-%d %H:%M:%S")
  echo "$curtime $log_prefix $@"
  echo "$curtime $log_prefix $@" >> $log_file_path
  #sleep 1
  if [ "$user" == "root" ]; then
    echo "$log_prefix [kmsg] $@" > $log_kmsg_path
    sleep 1
    #echo "$curtime $log_prefix [con] $@" > $log_con_path
    #sleep 1
  fi
}

function log_from_file()
{
  tmpfile=$@
  if [ ! -f "$tmpfile" ]; then
    log "no file [$tmpfile] to log"
    return 1
  fi

  declare_i_arr lists
  while IFS= read -r line;
  do
    add_i_arr_el lists "$line"
  done <$tmpfile

  # 定义日志时间格式
  local curtime=$(date "+%Y-%m-%d %H:%M:%S")

  #echo "$curtime $log_prefix $@"
  #echo "$curtime $log_prefix $@" >>$log_file_path
  local i=0
  get_i_arr_indices lists indices
  for i in $indices
  do
    echo "$curtime $log_prefix ${line}"
    echo "$curtime $log_prefix ${line}" >>$log_file_path
  done

  if [ "$user" == "root" ]; then
    #echo "$log_prefix [kmsg] $@" >$log_kmsg_path
    get_i_arr_indices lists indices
    for i in $indices
    do
      echo "$curtime $log_prefix ${line}" >$log_kmsg_path
      [ $(( i%10 )) -ne 9 ] || sleep 1
    done

    #sleep 1
  fi
}

# get Work Dir
function get_work_dir()
{
  ################
  # /etc/kpc/firstboot/guest/huangdi-customize-openwrt.sh
  # /etc/kpc/firstboot/guest/huangdi-first-boot.sh
  # /etc/kpc/firstboot/root/etc/rc.local
  # /etc/rc.local
  # /kpcos/distro/huangdi/releases/1.04/targets/x86/64/guest/huangdi-customize-openwrt.sh
  # /kpcos/distro/huangdi/releases/1.04/targets/x86/64/root/etc/rc.local
  ################

  local real_path=$(realpath $0)
  GLB_REAL_PATH="$real_path"
  log "REAL PATH is [$GLB_REAL_PATH]"

  GLB_WORK_DIR=$(dirname "$real_path")
  log "WORK DIR is [$GLB_WORK_DIR]"

  local done_file="${real_path}_done"
  log "done_file=[$done_file]"
  real_done_file=$(realpath "$done_file")
  log "real_done_file=[$real_done_file]"

  GLB_DONE_FILE="$real_done_file"
  log "GLB_DONE_FILE=[$GLB_DONE_FILE]"

  GLB_REBOOT_COUNTER=$GLB_WORK_DIR/reboot_counter
  log "GLB_REBOOT_COUNTER=$GLB_REBOOT_COUNTER"
  if [ ! -f $GLB_REBOOT_COUNTER ]; then
    echo "0" >$GLB_REBOOT_COUNTER
  fi
}

# loop forever to reboot
function force_reboot()
{
  log "force reboot now!"
  while true; do reboot; sleep 9; done
}

function check_reboot_counter()
{
  local reboot_counter=$(cat $GLB_REBOOT_COUNTER)
  reboot_counter=$((reboot_counter + 1))
  log "reboot counter is [$reboot_counter]"
  if [ $reboot_counter -gt 9 ]; then
    log "reboot too many times, exit now!"
    exit 1
  else
    log "set reboot counter to [$reboot_counter]"
    echo "$reboot_counter" >$GLB_REBOOT_COUNTER
  fi
}

function reset_reboot_counter()
{
  log "reset reboot counter"
  echo "0" >$GLB_REBOOT_COUNTER
}

# check WAN interface
function check_wan_iface()
{
  local COUNTER=0
  local dev_array="$(ip route | awk '/default/ {print $5}')"
  local iface_dev=$(echo $dev_array | awk '{print $1}')
  while [ "$iface_dev"x == x ]; do
    sleep 1
    COUNTER=$((COUNTER + 1))
    if [ $COUNTER -gt 29 ]; then
      log "Can't get default route device interface, exit now"
      exit 1
    fi
    dev_array="$(ip route | awk '/default/ {print $5}')"
    iface_dev=$(echo $dev_array | awk '{print $1}')
  done

  COUNTER=0
  local WAN_IP=$(ip addr show $iface_dev | grep "inet" | head -n 1 | awk '/inet/ {print $2}' | cut -d'/' -f1)
  while [ "${WAN_IP}"x == x ]; do
    sleep 1
    COUNTER=$((COUNTER + 1))
    if [ $COUNTER -gt 29 ]; then
      log "Can't get WAN IP address, reboot now"
      force_reboot
    fi
    WAN_IP=$(ip addr show $iface_dev | grep "inet" | head -n 1 | awk '/inet/ {print $2}' | cut -d'/' -f1)
  done
  log "WAN IP=[${WAN_IP}]"
}

# check WAN interface
function ubus_check_wan_iface()
{
  local COUNTER=0
  WAN_IP=$(ubus call network.interface.wan status | grep "address" | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}')
  while [ "${WAN_IP}"x == x ]; do
    sleep 1
    COUNTER=$((COUNTER + 1))
    if [ $COUNTER -gt 29 ]; then
      log "Can't get WAN IP address, reboot now"
      force_reboot
    fi
    WAN_IP=$(ubus call network.interface.wan status | grep "address" | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}')
  done
  log "WAN IP=[${WAN_IP}]"
}

# save installed packages list
function save_pkg_list()
{
  if [ "$1" == "" ]; then
    log "save_pkg_list() filename is empty, do nothing!"
    return
  fi
  local list_file="$PWD"/$1
  log "save $inst_type packages list to $list_file"
  [ -f $list_file ] || opkg list-installed >$list_file
}

# start kpc-heartbeat
function start_heartbeat()
{
  heartbeat_conf_dir=/etc/kpc
  heartbeat_conf_file=/etc/kpc/heartbeat.conf
  heartbeat_file=/usr/sbin/kpc-heartbeat.sh
  heartbeat_lock=/tmp/kpc-hearbeat.lock
  if [ ! -f $heartbeat_conf_file ]; then
    mkdir -p $heartbeat_conf_dir
    echo 9 >$heartbeat_conf_file
  fi
  if [ -x $heartbeat_file ]; then
    log "start kpc-heartbeat"
    (flock -n $heartbeat_lock -c "($heartbeat_file)")&
  fi
}

# run bootstrap configurating
function run_bootstrap_config()
{
  local admin_ssh_port=""
  local admin_http_port=""
  local admin_https_port=""
  local admin_ttyd_port=""
  local admin_password=""
  local admin_username=""
  local lc_language=""
  local lc_charset=""
  local swap_filesize=""
  local wifi_backend=""
  local wifi_dev=""
  local wifi_addr=""
  local wifi_mode=""
  local wifi_net=""
  local wifi_pass=""

  local conf_file=/etc/kpc/bootstrap.conf
  if [ -f $conf_file ]; then
    log "start to configurate bootstrap environment"

    declare_i_arr lists
    while IFS= read -r line;
    do
      add_i_arr_el lists "$line"
    done <$conf_file

    local i=0
    get_i_arr_indices lists indices
    for i in $indices
    do
      get_i_arr_val lists $i line
      #log "lists[$i]=[${line}]"
      local name=$(echo ${line} | awk '{print $1}')
      local val=$(echo ${line} | awk '{print $2}')
      #log "name=[$name] val=[$val]"
      case "$name" in
        "#"* )
          #log "it's comment"
          ;;
        "" )
          #log "it's empty line"
          ;;
        "admin.ssh_port" )
          admin_ssh_port="$val"
          if [ $admin_ssh_port -gt 65535 ]; then
            log "admin.ssh_port=[$admin_ssh_port] is invalid"
            continue;
          fi
          if [ $admin_ssh_port -lt 22 ]; then
            log "admin.ssh_port=[$admin_ssh_port] is invalid"
            continue;
          fi
          log "admin SSH port set to [$admin_ssh_port]"
          GLB_ADMIN_SSH_PORT=$admin_ssh_port
          ;;
        "admin.http_port" )
          admin_http_port="$val"
          if [ $admin_http_port -gt 65535 ]; then
            log "admin.http_port=[$admin_http_port] is invalid"
            continue;
          fi
          if [ $admin_http_port -lt 80 ]; then
            log "admin.http_port=[$admin_http_port] is invalid"
            continue;
          fi
          log "admin HTTP port set to [$admin_http_port]"
          GLB_ADMIN_HTTP_PORT=$admin_http_port
          ;;
        "admin.https_port" )
          admin_https_port="$val"
          if [ $admin_https_port -gt 65535 ]; then
            log "admin.https_port=[$admin_https_port] is invalid"
            continue;
          fi
          if [ $admin_https_port -lt 443 ]; then
            log "admin.https_port=[$admin_https_port] is invalid"
            continue;
          fi
          log "admin HTTPS port set to [$admin_https_port]"
          GLB_ADMIN_HTTPS_PORT=$admin_https_port
          ;;
        "admin.ttyd_port" )
          admin_ttyd_port="$val"
          if [ $admin_ttyd_port -gt 65535 ]; then
            log "admin.ttyd_port=[$admin_ttyd_port] is invalid"
            continue;
          fi
          if [ $admin_ttyd_port -lt 7681 ]; then
            log "admin.ttyd_port=[$admin_ttyd_port] is invalid"
            continue;
          fi
          log "admin TTYD port set to [$admin_ttyd_port]"
          GLB_ADMIN_TTYD_PORT=$admin_ttyd_port
          ;;
        "admin.password" )
          admin_password="$val"
          log "admin pasword set to [$admin_password]"
          GLB_ADMIN_PASSWORD=$admin_password
          ;;
        "admin.username" )
          admin_username="$val"
          log "admin username set to [$admin_username]"
          GLB_ADMIN_USERNAME=$admin_username
          ;;
        "locale.language" )
          lc_language="$val"
          log "LANGUAGE set to [$lc_language]"
          GLB_LC_LANGUAGE=$lc_language
          ;;
        "locale.charset" )
          lc_charset="$val"
          log "CHARSET set to [$lc_charset]"
          GLB_LC_CHARSET=$lc_charset
          ;;
        "swap.filesize" )
          swap_filesize="$val"
          log "SWAP file size set to [$swap_filesize]"
          GLB_SWAP_FILESIZE=$swap_filesize
          ;;
        "wifi.backend" )
          if [ "$val" == "iwd" ]; then
            log "enable iwd network configuration"
            wifi_backend="$val"
            iwd_main_conf=/etc/iwd/main.conf
            sed "s/#EnableNetworkConfiguration=true/EnableNetworkConfiguration=true/g" -i $iwd_main_conf
            #log_from_file $iwd_main_conf
          fi
          ;;
        "wifi.device_name" )
          wifi_dev="$val"
          log "wifi_dev=[$wifi_dev]"
          ;;
        "wifi.device_address" )
          wifi_addr="$val"
          log "wifi_addr=[$wifi_addr]"
          ;;
        "wifi.mode" )
          wifi_mode="$val"
          log "wifi_mode=[$wifi_mode]"
          ;;
        "wifi.network" )
          wifi_net="$val"
          log "wifi_net=[$wifi_net]"
          ;;
        "wifi.passphrase" )
          wifi_pass="$val"
          log "wifi_pass=[$wifi_pass]"
          ;;
        * )
          log "unknown option=[$name]"
          ;;
      esac
    done
  fi
}

opkg_install_pkg()
{
  PKG_NAME=$1
  log "opkg install $PKG_NAME"

  if [ "${PKG_NAME}"x == x ]; then
    log "Error: PKG_NAME is empty!!!"
    force_reboot
  fi

  tmpfile=$(mktemp)
  opkg install $PKG_NAME 2>&1 | tee $tmpfile
  log_from_file $tmpfile
  rm -f $tmpfile

  COUNTER=0
  PKG_INSTALLED=$(opkg list-installed | grep "^$PKG_NAME -" | awk '{print $1}')
  while [ "${PKG_INSTALLED}"x != "${PKG_NAME}"x ]; do
    log "Try to install $PKG_NAME again"
    sleep 1
    COUNTER=$((COUNTER + 1))
    if [ $COUNTER -gt 29 ]; then
      log "Can't install $PKG_NAME , reboot now"
      force_reboot
    fi
    tmpfile=$(mktemp)
    opkg update 2>&1 | tee $tmpfile
    log_from_file $tmpfile
    rm -f $tmpfile
    tmpfile=$(mktemp)
    opkg install $PKG_NAME 2>&1 | tee $tmpfile
    log_from_file $tmpfile
    rm -f $tmpfile
    PKG_INSTALLED=$(opkg list-installed | grep "^$PKG_NAME -" | awk '{print $1}')
  done
}

opkg_remove_force_depends_pkg()
{
  PKG_NAME=$1
  log "opkg remove --force-depends $PKG_NAME"

  if [ "${PKG_NAME}"x == x ]; then
    log "Error: PKG_NAME is empty!!!"
    force_reboot
  fi

  tmpfile=$(mktemp)
  opkg remove --force-depends $PKG_NAME 2>&1 | tee $tmpfile
  log_from_file $tmpfile
  rm -f $tmpfile

  COUNTER=0
  PKG_REMOVED=$(opkg list-installed | grep "^$PKG_NAME -" | awk '{print $1}')
  while [ "$PKG_REMOVED" == "$PKG_NAME" ]; do
    log "Try to remove $PKG_NAME again"
    sleep 1
    COUNTER=$((COUNTER + 1))
    if [ $COUNTER -gt 29 ]; then
      log "Can't remove $PKG_NAME , reboot now"
      force_reboot
    fi
    tmpfile=$(mktemp)
    opkg remove --force-depends $PKG_NAME 2>&1 | tee $tmpfile
    log_from_file $tmpfile
    rm -f $tmpfile
    PKG_REMOVED=$(opkg list-installed | grep "^$PKG_NAME -" | awk '{print $1}')
  done
}

# 0. init script
log_init
log "[customize-openwrt] START"
get_work_dir
if [ -f $GLB_DONE_FILE ]; then
  log "exist file $GLB_DONE_FILE , exit now"
  exit 1
fi
cd "$GLB_WORK_DIR"
check_reboot_counter
start_heartbeat
run_bootstrap_config
#check_wan_iface
ubus_check_wan_iface
save_pkg_list pre_customize_openwrt_pkgs.txt

log "PATH=[$PATH]"

# 0. enable swap
log "enable swap"
fstab_file=/etc/fstab
sys_swapfile=/swapfile
if [ x"$GLB_SWAP_FILESIZE" != x ]; then
  swapfile_size="$GLB_SWAP_FILESIZE"
  if [ ${#swapfile_size} -lt 2 ]; then
    swapfile_size=1G
    final=${swapfile_size: -1}
  else
    final=${swapfile_size: -1}
    case "$final" in
      "G" ) ;;
      "M" ) ;;
      * )
        log "[$final] unit is incorrect, use default 1G"
        swapfile_size=1G
        final=${swapfile_size: -1}
        ;;
    esac

    start=${swapfile_size:0:1}
    case "$start" in
      [1-9] ) ;;
      * )
        log "[$start] as begin charactor is incorrect, use default 1G"
        log "begin char must be digit of [1-9]"
        swapfile_size=1G
        final=${swapfile_size: -1}
      ;;
    esac

    middle=$(echo $img_size | awk '{print substr($0,2,length($0)-2)}')
    case "$middle" in
      [0-9] ) ;;
      "" ) ;;
      * )
        log "[$middle] is not digit [0-9] or empty string, use default 1G"
        swapfile_size=1G
        final=${swapfile_size: -1}
        ;;
    esac
  fi
else
  swapfile_size=1G
  final=${swapfile_size: -1}
fi

# set std_val as in (MB) unit
val=$(echo $swapfile_size | awk '{print substr($0,1,length($0)-1)}')
if [ "$final" == "G" ]; then
  std_val=$((val * 1024))
else
  std_val=$((val * 1))
fi
std_size="${std_val}M"
log "std_size=[$std_size]"

swapon_file=$(swapon | grep "$sys_swapfile" | awk '{print $1}')
if [ "$swapon_file" != "$sys_swapfile" ]; then
  #fallocate -l $swapfile_size $sys_swapfile
  # allocate swap file
  #dd if=/dev/zero of=/swapfile bs=1M count=1024
  dd if=/dev/zero of=$sys_swapfile bs=1M count=$std_val
  chmod 0600 $sys_swapfile
  mkswap $sys_swapfile
  swapon $sys_swapfile
fi

read_line=$(grep "$sys_swapfile swap swap defaults 0 0" $fstab_file)
log "read_line=[$read_line]"
if [ x"$read_line" == x ]; then
  log "add [$sys_swapfile swap swap defaults 0 0] to $fstab_file"
  echo "$sys_swapfile swap swap defaults 0 0" >>$fstab_file
fi

# 1. change password
# 1. change password
if [ x"$GLB_ADMIN_PASSWORD" != x ]; then
  def_passwd="$GLB_ADMIN_PASSWORD"
else
  def_passwd="KoudaiPC@123"
fi
log "default root password is [$def_passwd]"
tmpfile=$(mktemp)
echo "$def_passwd" >$tmpfile
echo "$def_passwd" >>$tmpfile
passwd root -a SHA512 <$tmpfile
rm -f $tmpfile

# 2. change ADMIN-SSH port
if [ x"$GLB_ADMIN_SSH_PORT" == x ]; then
  # use default port 50022
  log "change dropbear port to 50022"
  uci set dropbear.main.Port=50022
  uci commit
else
  # use setting port $GLB_ADMIN_SSH_PORT
  log "change dropbear port to $GLB_ADMIN_SSH_PORT"
  uci set dropbear.main.Port=$GLB_ADMIN_SSH_PORT
  uci commit
fi
service dropbear restart

# 3. remove uhttpd & dnsmasq
#opkg remove --force-depends uhttpd
#opkg remove --force-depends dnsmasq
opkg_remove_force_depends_pkg uhttpd
opkg_remove_force_depends_pkg dnsmasq

# 4. change opkg download URL
if [ ! -f /etc/opkg/distfeeds.conf.ow ]; then
  cp -f /etc/opkg/distfeeds.conf /etc/opkg/distfeeds.conf.ow
fi
sed "s#downloads.openwrt.org#mirrors.aliyun.com/openwrt#g" -i /etc/opkg/distfeeds.conf
tmpfile=$(mktemp)
opkg update 2>&1 | tee $tmpfile
log_from_file $tmpfile
rm -f $tmpfile

# 5. install nginx
#opkg install nginx-ssl
opkg_install_pkg nginx-ssl

# 6. setup ADMIN-HTTPS port
uci delete nginx._lan.listen
if [ x"$GLB_ADMIN_HTTPS_PORT" == x ]; then
  uci add_list nginx._lan.listen='50443 ssl default_server'
  uci add_list nginx._lan.listen='[::]:50443 ssl default_server'
  uci commit
else
  uci add_list nginx._lan.listen="$GLB_ADMIN_HTTPS_PORT ssl default_server"
  uci add_list nginx._lan.listen="[::]:$GLB_ADMIN_HTTPS_PORT ssl default_server"
  uci commit
fi

# 7. setup ADMIN-HTTP port redirect
uci delete nginx._redirect2ssl.listen
if [ x"$GLB_ADMIN_HTTP_PORT" == x ]; then
  uci add_list nginx._redirect2ssl.listen='50080'
  uci add_list nginx._redirect2ssl.listen='[::]:50080'
  if [ x"$GLB_ADMIN_HTTPS_PORT" == x ]; then
    uci set nginx._redirect2ssl.return='302 https://$host:50443$request_uri'
  else
    uci set nginx._redirect2ssl.return='302 https://$host:'"$GLB_ADMIN_HTTPS_PORT"'$request_uri'
  fi
  uci commit
else
  uci add_list nginx._redirect2ssl.listen="$GLB_ADMIN_HTTP_PORT"
  uci add_list nginx._redirect2ssl.listen="[::]:$GLB_ADMIN_HTTP_PORT"
  if [ x"$GLB_ADMIN_HTTPS_PORT" == x ]; then
    uci set nginx._redirect2ssl.return='302 https://$host:50443$request_uri'
  else
    uci set nginx._redirect2ssl.return='302 https://$host:'"$GLB_ADMIN_HTTPS_PORT"'$request_uri'
  fi
  uci commit
fi

# 8. remove restrict locally
sed "s#deny all;#allow all;#g" -i /etc/nginx/restrict_locally

# 9. install Standard OpenWRT set
#opkg install luci-nginx
opkg_install_pkg luci-nginx

# 10. restart nginx HTTP service
service nginx restart

# 11. install bind name service
#opkg install bind-tools
#opkg install bind-server
#opkg install bind-client
opkg_install_pkg bind-tools
opkg_install_pkg bind-server
opkg_install_pkg bind-client
sed "s#/tmp/bind/named.conf.local#/etc/bind/named.conf.local#g" -i /etc/bind/named.conf
touch /etc/bind/named.conf.local

# 12. install acme for Let's Encrypt SSL certificates
#opkg install acme
#opkg install acme-acmesh-dnsapi
#opkg install luci-app-acme
#opkg install luci-i18n-acme-zh-cn
opkg_install_pkg acme
opkg_install_pkg acme-acmesh-dnsapi
opkg_install_pkg luci-app-acme
opkg_install_pkg luci-i18n-acme-zh-cn

# 13. install docker
#opkg install docker
#opkg install dockerd
#opkg install luci-app-dockerman
#opkg install luci-i18n-dockerman-zh-cn
opkg_install_pkg docker
opkg_install_pkg dockerd
opkg_install_pkg luci-app-dockerman
opkg_install_pkg luci-i18n-dockerman-zh-cn

# 14. install ttyd
#opkg install ttyd
#opkg install luci-app-ttyd
#opkg install luci-i18n-ttyd-zh-cn
opkg_install_pkg ttyd
opkg_install_pkg luci-app-ttyd
opkg_install_pkg luci-i18n-ttyd-zh-cn

# 15. customize for Chinese
#opkg install luci-i18n-base-zh-cn
#opkg install luci-i18n-firewall-zh-cn
#opkg install luci-i18n-package-manager-zh-cn
opkg_install_pkg luci-i18n-base-zh-cn
opkg_install_pkg luci-i18n-firewall-zh-cn
opkg_install_pkg luci-i18n-package-manager-zh-cn

# 16. install diff tools
opkg install diffutils

# 17. setup wan6 interface
uci set network.wan6=interface
uci set network.wan6.proto=dhcpv6
uci set network.wan6.device=eth0
uci set network.wan6.reqaddress=try
uci set network.wan6.reqprefix=auto
uci set network.wan6.norelease=1
uci set network.globals.packet_steering=1
uci commit

# 18. setup firewall
uci set firewall.@defaults[0].synflood_protect=1
uci set firewall.@defaults[0].drop_invalid=1

result=$(uci get firewall.@redirect[0])
if [ $result == "redirect" ]; then
  log "has firewall.@redirect[0]"
else
  uci add firewall redirect
fi
uci set firewall.@redirect[0]=redirect
uci set firewall.@redirect[0].dest='lan'
uci set firewall.@redirect[0].target='DNAT'
uci set firewall.@redirect[0].name='SSH-ADMIN'
uci set firewall.@redirect[0].family='ipv4'
uci set firewall.@redirect[0].proto='tcp'
uci set firewall.@redirect[0].src='wan'
uci set firewall.@redirect[0].dest_ip='192.168.1.1'
if [ x"$GLB_ADMIN_SSH_PORT" == x ]; then
  uci set firewall.@redirect[0].src_dport='50022'
  uci set firewall.@redirect[0].dest_port='50022'
else
  uci set firewall.@redirect[0].src_dport="$GLB_ADMIN_SSH_PORT"
  uci set firewall.@redirect[0].dest_port="$GLB_ADMIN_SSH_PORT"
fi

result=$(uci get firewall.@redirect[1])
if [ $result == "redirect" ]; then
  log "has firewall.@redirect[1]"
else
  uci add firewall redirect
fi
uci set firewall.@redirect[1]=redirect
uci set firewall.@redirect[1].dest='lan'
uci set firewall.@redirect[1].target='DNAT'
uci set firewall.@redirect[1].name='SSH-ADMIN6'
uci set firewall.@redirect[1].family='ipv6'
uci set firewall.@redirect[1].proto='tcp'
uci set firewall.@redirect[1].src='wan'
if [ x"$GLB_ADMIN_SSH_PORT" == x ]; then
  uci set firewall.@redirect[1].src_dport='50022'
  uci set firewall.@redirect[1].dest_port='50022'
else
  uci set firewall.@redirect[1].src_dport="$GLB_ADMIN_SSH_PORT"
  uci set firewall.@redirect[1].dest_port="$GLB_ADMIN_SSH_PORT"
fi

result=$(uci get firewall.@redirect[2])
if [ $result == "redirect" ]; then
  log "has firewall.@redirect[2]"
else
  uci add firewall redirect
fi
uci set firewall.@redirect[2]=redirect
uci set firewall.@redirect[2].dest='lan'
uci set firewall.@redirect[2].target='DNAT'
uci set firewall.@redirect[2].name='HTTP-ADMIN'
uci set firewall.@redirect[2].family='ipv4'
uci set firewall.@redirect[2].proto='tcp'
uci set firewall.@redirect[2].src='wan'
uci set firewall.@redirect[2].dest_ip='192.168.1.1'
if [ x"$GLB_ADMIN_HTTP_PORT" == x ]; then
  uci set firewall.@redirect[2].src_dport='50080'
  uci set firewall.@redirect[2].dest_port='50080'
else
  uci set firewall.@redirect[2].src_dport="$GLB_ADMIN_HTTP_PORT"
  uci set firewall.@redirect[2].dest_port="$GLB_ADMIN_HTTP_PORT"
fi

result=$(uci get firewall.@redirect[3])
if [ $result == "redirect" ]; then
  log "has firewall.@redirect[3]"
else
  uci add firewall redirect
fi
uci set firewall.@redirect[3]=redirect
uci set firewall.@redirect[3].dest='lan'
uci set firewall.@redirect[3].target='DNAT'
uci set firewall.@redirect[3].name='HTTP-ADMIN6'
uci set firewall.@redirect[3].family='ipv6'
uci set firewall.@redirect[3].proto='tcp'
uci set firewall.@redirect[3].src='wan'
if [ x"$GLB_ADMIN_HTTP_PORT" == x ]; then
  uci set firewall.@redirect[3].src_dport='50080'
  uci set firewall.@redirect[3].dest_port='50080'
else
  uci set firewall.@redirect[3].src_dport="$GLB_ADMIN_HTTP_PORT"
  uci set firewall.@redirect[3].dest_port="$GLB_ADMIN_HTTP_PORT"
fi

result=$(uci get firewall.@redirect[4])
if [ $result == "redirect" ]; then
  log "has firewall.@redirect[4]"
else
  uci add firewall redirect
fi
uci set firewall.@redirect[4]=redirect
uci set firewall.@redirect[4].dest='lan'
uci set firewall.@redirect[4].target='DNAT'
uci set firewall.@redirect[4].name='HTTPS-ADMIN'
uci set firewall.@redirect[4].family='ipv4'
uci set firewall.@redirect[4].proto='tcp'
uci set firewall.@redirect[4].src='wan'
uci set firewall.@redirect[4].dest_ip='192.168.1.1'
if [ x"$GLB_ADMIN_HTTPS_PORT" == x ]; then
  uci set firewall.@redirect[4].src_dport='50443'
  uci set firewall.@redirect[4].dest_port='50443'
else
  uci set firewall.@redirect[4].src_dport="$GLB_ADMIN_HTTPS_PORT"
  uci set firewall.@redirect[4].dest_port="$GLB_ADMIN_HTTPS_PORT"
fi

result=$(uci get firewall.@redirect[5])
if [ $result == "redirect" ]; then
  log "has firewall.@redirect[5]"
else
  uci add firewall redirect
fi
uci set firewall.@redirect[5]=redirect
uci set firewall.@redirect[5].dest='lan'
uci set firewall.@redirect[5].target='DNAT'
uci set firewall.@redirect[5].name='HTTPS-ADMIN6'
uci set firewall.@redirect[5].family='ipv6'
uci set firewall.@redirect[5].proto='tcp'
uci set firewall.@redirect[5].src='wan'
if [ x"$GLB_ADMIN_HTTPS_PORT" == x ]; then
  uci set firewall.@redirect[5].src_dport='50443'
  uci set firewall.@redirect[5].dest_port='50443'
else
  uci set firewall.@redirect[5].src_dport="$GLB_ADMIN_HTTPS_PORT"
  uci set firewall.@redirect[5].dest_port="$GLB_ADMIN_HTTPS_PORT"
fi

uci commit


# 19. setup dockerd
uci set dockerd.globals.iptables='0'
uci delete dockerd.globals.registry_mirrors
uci add_list dockerd.globals.registry_mirrors='https://hub.rat.dev'
uci add_list dockerd.globals.registry_mirrors='https://lynn520.xyz'

uci commit

# 20. remove iptables
#opkg remove --force-depends iptables-zz-legacy
#opkg remove --force-depends iptables-mod-extra
#opkg remove --force-depends ip6tables-zz-legacy

# 21. setup ttyd
uci set ttyd.@ttyd[0].interface='br-lan'
uci set ttyd.@ttyd[0].command='/bin/login'
if [ x"$GLB_ADMIN_TTYD_PORT" == x ]; then
  uci set ttyd.@ttyd[0].port='57681'
else
  uci set ttyd.@ttyd[0].port="$GLB_ADMIN_TTYD_PORT"
fi
uci set ttyd.@ttyd[0].uid='0'
uci set ttyd.@ttyd[0].gid='0'
uci set ttyd.@ttyd[0].ssl='1'
uci set ttyd.@ttyd[0].ssl_cert='/etc/nginx/conf.d/_lan.crt'
uci set ttyd.@ttyd[0].ssl_key='/etc/nginx/conf.d/_lan.key'
uci set ttyd.@ttyd[0].debug='7'
uci set ttyd.@ttyd[0].once='1'
uci set ttyd.@ttyd[0].ipv6='1'

uci commit

# 22. add port-forwarding for ttyd
result=$(uci get firewall.@redirect[6])
if [ $result == "redirect" ]; then
  log "has firewall.@redirect[6]"
else
  uci add firewall redirect
fi
uci set firewall.@redirect[6]=redirect
uci set firewall.@redirect[6].dest='lan'
uci set firewall.@redirect[6].target='DNAT'
uci set firewall.@redirect[6].name='TTYD-ADMIN'
uci set firewall.@redirect[6].family='ipv4'
uci set firewall.@redirect[6].proto='tcp'
uci set firewall.@redirect[6].src='wan'
uci set firewall.@redirect[6].dest_ip='192.168.1.1'
if [ x"$GLB_ADMIN_TTYD_PORT" == x ]; then
  uci set firewall.@redirect[6].src_dport='57681'
  uci set firewall.@redirect[6].dest_port='57681'
else
  uci set firewall.@redirect[6].src_dport="$GLB_ADMIN_TTYD_PORT"
  uci set firewall.@redirect[6].dest_port="$GLB_ADMIN_TTYD_PORT"
fi

result=$(uci get firewall.@redirect[7])
if [ $result == "redirect" ]; then
  log "has firewall.@redirect[7]"
else
  uci add firewall redirect
fi
uci set firewall.@redirect[7]=redirect
uci set firewall.@redirect[7].dest='lan'
uci set firewall.@redirect[7].target='DNAT'
uci set firewall.@redirect[7].name='TTYD-ADMIN6'
uci set firewall.@redirect[7].family='ipv6'
uci set firewall.@redirect[7].proto='tcp'
uci set firewall.@redirect[7].src='wan'
if [ x"$GLB_ADMIN_TTYD_PORT" == x ]; then
  uci set firewall.@redirect[7].src_dport='57681'
  uci set firewall.@redirect[7].dest_port='57681'
else
  uci set firewall.@redirect[7].src_dport="$GLB_ADMIN_TTYD_PORT"
  uci set firewall.@redirect[7].dest_port="$GLB_ADMIN_TTYD_PORT"
fi

uci commit

# 23. enable ttylonin
uci set system.@system[0].ttylogin='1'

uci commit

# 24. set hostname
uci set system.@system[0].hostname='HuangDi'

uci commit

# 25. set timezone
opkg install zoneinfo-all 

uci set system.@system[0].timezone='CST-8'
uci set system.@system[0].zonename='Asia/Shanghai'
uci set system.@system[0].log_proto='udp'
uci set system.@system[0].conloglevel='8'
uci set system.@system[0].cronloglevel='7'

uci commit

# 26. set luci language
uci set luci.main.lang='zh_cn'

uci commit

# 27. set luci theme
uci set luci.main.mediaurlbase='/luci-static/bootstrap-dark'

uci commit

# 28. install sftp server
#opkg install openssh-sftp-server
opkg_install_pkg openssh-sftp-server

# 29. enable swap
#dd if=/dev/zero of=/swapfile bs=1M count=1024
#chmod 0600 /swapfile
#mkswap /swapfile
#swapon /swapfile
#echo "/swapfile swap swap defaults 0 0" >> /etc/fstab
#line_no=$(grep -n "exit 0" /etc/rc.local | awk '{split($0,a,":"); print a[1]}')

# 30. remove uhttpd & dnsmasq
#opkg remove --force-depends uhttpd 2>&1 | tee /dev/kmsg
#opkg remove --force-depends dnsmasq 2>&1 | tee /dev/kmsg
opkg_remove_force_depends_pkg uhttpd
opkg_remove_force_depends_pkg dnsmasq

# 31. remove iptables
#opkg remove --force-depends iptables-zz-legacy
#opkg remove --force-depends iptables-mod-extra
#opkg remove --force-depends ip6tables-zz-legacy
opkg_remove_force_depends_pkg iptables-zz-legacy
opkg_remove_force_depends_pkg iptables-mod-extra
opkg_remove_force_depends_pkg ip6tables-zz-legacy

save_pkg_list post_customize_openwrt_pkgs.txt
touch $GLB_DONE_FILE
sync
sleep 1

log "[customize-openwrt] EXIT"
sleep 1

# restart system
reset_reboot_counter
#poweroff
